import {
  _decorator,
  Component,
  Node,
  UITransform,
  Sprite,
  Animation,
  SpriteFrame,
  AnimationClip,
  animation,
  utils,
} from 'cc'
const { ccclass, property } = _decorator

// 引入事件中心
import EventManager from '../../Runtime/EventManager'
import DataManager from '../../Runtime/DataManager'

// 实体类型
// import { EntityManager } from '../../Base/EntityManager'
import { SkeletonManager } from '../../Base/SkeletonManager'

// 状态机
import { WoodenskeletonStateMchine } from './WoodenskeletonStateMchine'

// 状态机类型
import { PLAYER_STATE_TYPE_ENUM, ENTITY_TYPE_ENUM } from '../../Enums'

// // utils
// import { generateRandomId } from '../../Utils'

// import { DIRECTION } from '../../Enums'

@ccclass('WoodenskeletonManager')
export class WoodenskeletonManager extends SkeletonManager {
  // id: string
  async init(pramers) {
    // this.id = generateRandomId()

    // 初始化状态机
    this.fsm = this.addComponent(WoodenskeletonStateMchine)
    await this.fsm.init()

    // 传入默认值
    super.init(pramers)

    // console.log('[ this.id ] >', this.id)

    // 注册事件
    EventManager.Instance.on('PLAYER_MOVE_END', this.judgeAttack, this)

  }

  onDestroy(): void {
    super.onDestroy()

    // 移除
    EventManager.Instance.off('PLAYER_MOVE_END', this.judgeAttack)
  }

  // 判断是否进行攻击
  judgeAttack() {
    const player = DataManager.Instance.player
    if (!player || this.state === PLAYER_STATE_TYPE_ENUM.DEATH) {
      return
    }

    const { x: playerX, y: playerY, state: playerState } = player
    const { x, y } = this
    const differenceX = Math.abs(x - playerX)
    const differenceY = Math.abs(y - playerY)

    // 判断不能攻击死亡的玩家
    if (
      ((playerX === x && differenceY <= 1) || (playerY === y && differenceX <= 1)) &&
      [PLAYER_STATE_TYPE_ENUM.DEATH, PLAYER_STATE_TYPE_ENUM.AIR_DEATH].indexOf(playerState) === -1
    ) {
      this.state = PLAYER_STATE_TYPE_ENUM.ATTACK
      EventManager.Instance.emit('ATTACK_PLAYER', 'DEATH')
    } else {
      this.state = PLAYER_STATE_TYPE_ENUM.IDLE
    }

    // console.log('[ this.state ] >', this.state, playerX, playerY, x, y)
  }

  // // 被玩家攻击
  // onDeath(id: string) {
  //   if (this.state === PLAYER_STATE_TYPE_ENUM.DEATH) {
  //     return
  //   }

  //   if (id === this.id) {
  //     this.state = PLAYER_STATE_TYPE_ENUM.DEATH
  //   }
  // }
}
